package org.linlinjava.litemall.admin.aop;

import com.github.pagehelper.PageHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.linlinjava.litemall.db.domain.LitemallAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author wj
 * @date 2021/9/10 13:36
 */
@Component
@Aspect
public class PageHelperAop {

    private final Logger logger = LoggerFactory.getLogger(PageHelperAop.class);
    /**
     * 切点 匹配service下所有方法
     */
    @Pointcut("execution(* org.linlinjava.litemall.admin.service..*.*(..))")
    public void pagehelper() {}


    @After("pagehelper()")
    public void clearAfter(JoinPoint joinPoint) {
        PageHelper.clearPage();
        // 记录下请求内容
//        logger.info("进入了切点：{}","删除未使用pagehelper记录");

    }


    @Before("pagehelper()")
    public void clearBeforeBack(JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            Subject currentUser = SecurityUtils.getSubject();
            LitemallAdmin admin = (LitemallAdmin) currentUser.getPrincipal();
            if (admin != null) {
                MDC.put("userId", admin.getId().toString());
                MDC.put("userName", admin.getUsername());
                MDC.put("phone", admin.getPhone());
                MDC.put("url", request.getRequestURI());
            }
        }catch (Exception ex) {
            logger.error("获取请求的用户信息异常:{}",ex);
        }
    }
}
